<template>
  <div>
    <Form
      :model="modelForm"
      ref="editForm"
      class="ivu-form-no-margin-bottom"
      :rules="rule"
      :label-width="100"
    >
      <Row :gutter="32" class="code-row-bg">
        <Col span="12" style="border:none;">
          <Form-item prop="treeName" :label="$t('module.treeManage.treeName')">
            <Input
              :placeholder="$t('module.treeManage.warning.enterTreeName')"
              v-model.trim="modelForm.treeName"
              style="width:90%"
              :maxlength="50"
              
            />
          </Form-item>
        </Col>
        <Col span="12" style="border:none;">
          <Form-item prop="treeCode" :label="$t('module.treeManage.treeCode')">
            <Input
              :placeholder="$t('module.treeManage.warning.enterTreeCode')"
              v-model.trim="modelForm.treeCode"
              style="width:90%"
              :disabled="treeId != null"
              
            />
          </Form-item>
        </Col>
      </Row>
      <Row :gutter="32" class="code-row-bg">
        <Col span="12" style="border:none;">
          <Form-item prop="treeType" :label="$t('module.treeManage.treeType')">
            <Select v-model="modelForm.treeType" style="width:90%"  :disabled="isEdit">
              <Option v-for="treeType in treeTypeList" :value="treeType.code" :key="treeType.code">
                {{
                treeType.name
                }}
              </Option>
            </Select>
          </Form-item>
        </Col>
        <Col span="12" style="border:none;">
          <Form-item prop="enabled" :label="$t('common.status')">
            <RadioGroup v-model="modelForm.enabled" size="small">
              <Radio :label="1">
                <span>{{ $t("common.enable") }}</span>
              </Radio>
              <Radio :label="0">
                <span>{{ $t("common.disable") }}</span>
              </Radio>
            </RadioGroup>
          </Form-item>
        </Col>
      </Row>
      <!-- <Row :gutter="32" class="code-row-bg">
        <Col span="12" style="border:none;">
          <Form-item prop="productCode" :label="$t('module.treeManage.productCode')">
            <Select
              v-model="modelForm.productCode"
              style="width:90%"
              :disabled="productCode != '' || treeId != null"
              clearable
              
            >
              <Option
                v-for="product in productList"
                :value="product.vsiKey"
                :key="product.vsiKey"
              >{{product.vsiValue}}</Option>
            </Select>
          </Form-item>
        </Col>
        <Col span="12" style="border:none;">
          <Form-item prop="tenantCode" :label="$t('module.treeManage.tenantCode')">
            <Select
              v-model="modelForm.tenantCode"
              style="width:90%"
              :disabled="tenantCode != null || treeId != null"
              clearable
              
            >
              <Option
                v-for="tenant in tenantList"
                :value="tenant.tenantCode"
                :key="tenant.tenantCode"
              >{{tenant.tenantName}}</Option>
            </Select>
          </Form-item>
        </Col>
      </Row>-->
      <Form-item prop="description" :label="$t('module.treeManage.description')">
        <Input
          v-model="modelForm.treeDesc"
          type="textarea"
          :rows="4"
          :maxlength="20"
          style="width:96%"
          
        />
      </Form-item>
      <!-- <Form-item prop="locked" :label="$t('common.status')">
        <RadioGroup v-model="modelForm.locked">
          <Radio v-model="modelForm.locked" label="1">{{$t('common.enable')}}</Radio>
          <Radio v-model="modelForm.locked" label="0">{{$t('common.disable')}}</Radio>
        </RadioGroup>
      </Form-item>-->
      <!-- <form-creator ref="formCreator" :formConfig="formConfig"/> -->
    </Form>
  </div>
</template>
<script>
import tenantAPI from "@/api/tenantApi.js";
import valueSetAPI from "@/api/valueSetAPI.js";
import treeFormConfig from "./TreeFormConfig.json";
import { cloneDeep } from "lodash";
import locales from "./locales.js";
import { codeReg } from "@/const.js";

export default {
  mixins: [locales],
  components: {},
  props: {
    treeId: {
      type: String,
      default() {
        return null;
      }
    },
    // productCode: {
    //   type: String,
    //   default: null
    // },
    tenantCode: {
      type: String,
      default: null
    }
  },
  data() {
    const validateTreeCode = (rule, value, callback) => {
      if (value === "") {
        callback(new Error(this.$t("module.treeManage.warning.enterTreeCode")));
      } else if (value.length > 30) {
        callback(new Error(this.$t("common.warning.codeCheckLength")));
      } else if (!new RegExp(codeReg).test(value)) {
        callback(new Error(this.$t("common.warning.codeCheckCharacter")));
      } else if (value.indexOf(" ") != -1) {
        callback(new Error(this.$t("module.treeManage.warning.treeCodeHaveSpace")));
      } else if (/\//.test(value)) {
        callback(new Error(this.$t("module.treeManage.warning.treeCodeHaveSlash")));
      }
      callback();
    };
    return {
      isEdit: false,
      treeTypeList: [],
      productList: [],
      tenantList: [],
      modelForm: {
        treeName: "",
        treeCode: "",
        treeType: "",
        // productCode: this.productCode,
        tenantCode: this.tenantCode,
        treeDesc: "",
        // source: "0",
        enabled: 1
      },
      rule: {
        treeName: [
          {
            required: true,
            message: this.$t("module.treeManage.warning.enterTreeName"),
            trigger: "blur"
          }
        ],
        treeCode: [
          {
            required: true,
            validator: validateTreeCode,
            trigger: "blur"
          }
        ],
        treeType: [
          {
            required: true,
            message: this.$t("module.treeManage.warning.enterTreeType"),
            trigger: "blur"
          }
        ]
      },
      formConfig: cloneDeep(treeFormConfig),
      actions: [
        {
          text: this.$t("common.save"),
          theme: "primary",
          handle: () => {
            this.save();
          },
          loading: false
        },
        {
          text: this.$t("common.close"),
          handle: () => {
            this.$emit("Close");
          }
        }
      ]
    };
  },
  computed: {},
  created: function() {
    this.init();
    if (this.treeId) {
      this.isEdit = true;
      this.$emit("SetTitle", this.$t("module.treeManage.editTree"));
    } else {
      this.$emit("SetTitle", this.$t("module.treeManage.creatTree"));
    }
    this.$emit("SetPageWidth", 700);
    this.$emit("SetPageActions", this.actions);
  },
  beforeMount: function() {},
  mounted: function() {},
  beforeDestroy: function() {},
  destroyed: function() {},
  methods: {
    init() {
      this.initTreeType();
      this.initProduct();
      this.initTenant();
      if (this.treeId) {
        window.$http.post(`${window.RPConfig.mgt}/tree/detail?treeId=${this.treeId}`).then(response => {
          this.modelForm = response.data;
          // this.$refs["formCreator"].fApi.setValue(response.data.attributeValue);
          // this.modelForm.treeName = response.data.treeName;
          // this.modelForm.treeCode = response.data.treeCode;
          // this.modelForm.treeType = response.data.treeType;
          // this.modelForm.treeDesc = response.data.treeDesc;
          // this.modelForm.enabled = response.data.enabled;
        });
      }
    },
    initTreeType() {
      window.$http.get(`${window.RPConfig.setting}/valueset/item/list?vsCode=treeType`).then(response => {
        for (const treeType of response.data) {
          this.treeTypeList.push({
            code: treeType.vsiKey,
            name: treeType.vsiValue
          });
        }
      });
    },
    // 初始化所属产品
    initProduct() {
      valueSetAPI.getValueSetByCode("RC_PRODUCT").then(data => {
        this.productList = data;
      });
    },
    // 初始化所属租户
    initTenant() {
      if (this.treeId) {
        tenantAPI.queryAllTenantList().then(data => {
          this.tenantList = data;
        });
      } else {
        tenantAPI.queryTenantList().then(data => {
          this.tenantList = data;
        });
      }
    },
    save() {
      this.$refs["editForm"].validate(valid => {
        // 验证扩展属性
        if (valid) {
          // 保存扩展属性
          // this.modelForm.attributeValue = this.$refs["formCreator"].fApi.formData();
          this.actions[0].loading = true;
          if (this.treeId) {
            window.$http
              .post(`${window.RPConfig.mgt}/tree/update`, this.modelForm)
              .then(response => {
                this.$message.success({
                  content: this.$t("common.updateSuccess"),
                  duration: 3
                });
                this.$emit("Close", true);
              })
              .catch(() => {
                this.actions[0].loading = false;
              });
          } else {
            window.$http
              .post(`${window.RPConfig.mgt}/tree/add`, this.modelForm)
              .then(response => {
                this.$message.success({
                  content: this.$t("common.createSuccess"),
                  duration: 3
                });
                this.$emit("Close", true);
              })
              .catch(() => {
                this.actions[0].loading = false;
              });
          }
        } else {
          this.actions[0].loading = false;
          this.$message.error({
            content: this.$t("common.formValidateFailed"),
            duration: 3
          });
          return 0;
        }
      });
    }
    // 验证扩展属性
    // formCreatorValidate() {
    //   let result = false;
    //   this.$refs["formCreator"].fApi.validate(
    //     () => {
    //       result = true;
    //     },
    //     () => {
    //       result = false;
    //     }
    //   );
    //   return result;
    // }
  },
  watch: {},
  directives: {}
};
</script>
<style lang="less" scoped>
.ivu-form-no-margin-bottom {
  .form-creator-box {
    .form-create {
      padding: 1px;
    }
  }
}
</style>
